package service

import (
	"errors"
	"ollama-go/dto"
	"ollama-go/entity"
	"ollama-go/query"
	"ollama-go/vo"

	"github.com/androidsr/sc-go/model"
	"github.com/androidsr/sc-go/sbuilder"
	"github.com/androidsr/sc-go/sc"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sno"
)

var apiPlatformInfoService *ApiPlatformInfoService

type ApiPlatformInfoService struct {
}

func NewApiPlatformInfoService() *ApiPlatformInfoService {
	if apiPlatformInfoService == nil {
		apiPlatformInfoService = new(ApiPlatformInfoService)
	}
	return apiPlatformInfoService
}

// 使用id获取数据
func (m ApiPlatformInfoService) Get(id string) *vo.ApiPlatformInfoVO {
	data := new(entity.ApiPlatformInfo)
	data.Id = id
	err := sgorm.DB.GetOne(data)
	if err != nil {
		return nil
	}
	return sc.Copy[vo.ApiPlatformInfoVO](data)
}

// 保存数据
func (m ApiPlatformInfoService) Save(dto *dto.ApiPlatformInfoDTO) error {
	data := sc.Copy[entity.ApiPlatformInfo](dto)
	data.Id = sno.GetString()
	err := sgorm.DB.Insert(data)
	return err
}
func (m ApiPlatformInfoService) SaveOrUpdate(dto *dto.ApiPlatformInfoDTO) error {
	var err error
	data := new(entity.ApiPlatformInfo)
	data.Id = dto.Id
	err = sgorm.DB.GetOne(data)
	if err != nil {
		return err
	}
	if data == nil && dto.Id == "" {
		err = m.Save(dto)
	} else {
		if data.PlatformName != dto.PlatformName {
			dto.Id = ""
			err = m.Save(dto)
		} else {
			err = m.UpdateById(dto)
		}
	}
	return err
}

// 更新数据
func (m ApiPlatformInfoService) UpdateById(dto *dto.ApiPlatformInfoDTO) error {
	dbEntity := new(entity.ApiPlatformInfo)
	dbEntity.Id = dto.Id
	sgorm.DB.GetOne(dbEntity)
	if dbEntity.TenantId != "" && dbEntity.TenantId != dto.TenantId {
		return errors.New("非本人创建不能修改")
	}
	sc.CopyTo(dto, dbEntity)
	err := sgorm.DB.UpdateById(dbEntity).Error
	return err
}

// 删除数据
func (m ApiPlatformInfoService) DeleteById(id string) error {
	err := NewApiRequestConfigService().DeleteByPlatformId(id)
	if err != nil {
		return err
	}
	err = sgorm.DB.DeleteById(entity.ApiPlatformInfo{}, id)
	return err
}

// 分页列表查询
func (m ApiPlatformInfoService) QueryPage(query *query.ApiPlatformInfoQueryDTO) *model.PageResult {
	sql := `select * from api_platform_info a `
	data := make([]entity.ApiPlatformInfo, 0)
	b := sbuilder.StructToBuilder(query, sql)
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, query.BaseQueryDTO.Page, sql, values...)
}

// 分页下拉查询
func (m ApiPlatformInfoService) QueryList(query *model.SelectQueryDTO) *model.PageResult {
	sql := `select a.id as value, a.platform_name as label from api_platform_info a where 1=1 `
	data := make([]model.SelectVO, 0)
	b := sbuilder.Builder(sql)
	b.Like("CONCAT(a.id,a.platform_name)", query.Label)
	for k, v := range query.Vars {
		b.Eq(k, v)
	}
	b.Multiple().Ors(b.In("a.id", query.Selected))
	sql, values := b.Build()
	return sgorm.DB.SelectPage(&data, &query.Page, sql, values...)
}
